package com.kejy.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kejy.entity.Auction;
import com.kejy.entity.AuctionUser;
import com.kejy.mapper.AuctionMapper;
import com.kejy.util.MyBatisUtil;
import com.kejy.util.RequestUtil;
import my.framework.anno.RequestMapping;
import org.springframework.ui.Model;  // ✅ Spring MVC 的 Model
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@MultipartConfig  // 必须添加这个注解，才能处理文件上传
public class AuctionServlet {

    @RequestMapping(value = "/addAuction")
    public void addAuction(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        SqlSession sqlSession = null;
        // 处理时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

        try {
            sqlSession = MyBatisUtil.createSqlSession();
            // 获取参数
            String auctionName = request.getParameter("auctionName");
            String auctionStartPrice = request.getParameter("auctionStartPrice");
            String auctionUpset = request.getParameter("auctionUpset");
            Date auctionStartTime = dateFormat.parse(request.getParameter("auctionStartTime"));
            Date auctionEndTime = dateFormat.parse(request.getParameter("auctionEndTime"));
            // 获取上传的文件
            Part filePart = request.getPart("auctionPic");
            String auctionPic = null;
            String auctionPicType = null;

            if (filePart != null && filePart.getSize() > 0) {
                auctionPic = filePart.getSubmittedFileName();  // 获取文件名
                auctionPicType = filePart.getContentType();    // 获取文件类型
                // 保存文件到服务器（可选）
                String uploadPath = request.getServletContext().getRealPath("/uploads");
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) uploadDir.mkdir();
                filePart.write(uploadPath + File.separator + auctionPic);
            } else {
                // 如果没有上传图片，设置默认值（或抛出错误）
                auctionPic = "ad20.jpg";  // 默认图片
                auctionPicType = "jpg"; // 图片类型
            }

            String auctionDesc = request.getParameter("auctionDesc");
            AuctionMapper mapper = sqlSession.getMapper(AuctionMapper.class);

            Auction auction = new Auction(auctionName, Double.parseDouble(auctionStartPrice), Double.parseDouble(auctionUpset),
                    auctionStartTime, auctionEndTime, auctionPic, auctionPicType, auctionDesc);

            mapper.addAuction(auction);
            sqlSession.commit();
            //  跳转到登录页面，使用绝对路径
            response.sendRedirect(request.getContextPath() + "/do/pageList");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @RequestMapping(value = "/pageList")
    public void selectByCondition(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            AuctionMapper mapper = sqlSession.getMapper(AuctionMapper.class);

            // 1. 获取分页参数
            int pageNum = RequestUtil.parseInt(request, "pageNum", 1);
            int pageSize = RequestUtil.parseInt(request, "pageSize", 5);

            // 确保pageSize有效（避免意外返回全部数据）
            if (pageSize <= 0 || pageSize > 100) {
                pageSize = 5; // 强制重置为默认值
            }

            // 2. 获取查询条件
            String auctionName = request.getParameter("auctionName");
            String auctionDesc = request.getParameter("auctionDesc");
            String startTimeStr = request.getParameter("auctionStartTime");
            String endTimeStr = request.getParameter("auctionEndTime");
            String startPriceStr = request.getParameter("auctionStartPrice");
            double startPrice = 0.0; // 默认值，根据业务需要设定

            if (startPriceStr != null && !startPriceStr.trim().isEmpty()) {
                try {
                    startPrice = Double.parseDouble(startPriceStr);
                } catch (NumberFormatException e) {
                    // 处理非法数字输入，例如记录日志或抛出异常
                    throw new IllegalArgumentException("起拍价参数必须为合法数字", e);
                }
            }

            // 3. 处理时间格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date auctionStartTime = null;
            Date auctionEndTime = null;
            Double auctionStartPrice = null;

            try {
                if (startTimeStr != null && !startTimeStr.isEmpty()) {
                    auctionStartTime = dateFormat.parse(startTimeStr);
                }
                if (endTimeStr != null && !endTimeStr.isEmpty()) {
                    auctionEndTime = dateFormat.parse(endTimeStr);
                }
                if (startPriceStr != null && !startPriceStr.isEmpty()) {
                    auctionStartPrice = new BigDecimal(startPriceStr).doubleValue();;
                }
            } catch (Exception e) {
                response.getWriter().write("参数格式错误");
                return;
            }

            // 4. 封装查询条件
            Auction auction = new Auction();
            auction.setAuctionName(auctionName);
            auction.setAuctionDesc(auctionDesc);
            auction.setAuctionStartTime(auctionStartTime);
            auction.setAuctionEndTime(auctionEndTime);
            auction.setAuctionStartPrice(auctionStartPrice);

            // 执行分页查询
            PageHelper.startPage(pageNum, pageSize);
            List<Auction> auctionList = mapper.selectByCondition(auction);
            PageInfo<Auction> pageInfo = new PageInfo<>(auctionList);

            // 检查用户是否登录
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("user") == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 获取登录用户信息
            AuctionUser user = (AuctionUser) session.getAttribute("user");
            boolean userIsAdmin = user.isUserIsAdmin();

            // 将数据存入session（因为要跨页面）
            session.setAttribute("pageInfo", pageInfo);
            session.setAttribute("queryParams", request.getParameterMap());

            // 根据用户权限处理不同逻辑
            if (userIsAdmin) {
                // 管理员逻辑登录
                response.sendRedirect(request.getContextPath() + "/auction_management.jsp");
            } else {
                // 普通用户登录
                response.sendRedirect(request.getContextPath() + "/auctionList.jsp");
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "查询失败");
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @RequestMapping(value = "/deleteAuction")
    public void deleteAuction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 获取当前页码（从请求参数或session中）
        int currentPage = RequestUtil.parseInt(request, "currentPage", 1);

        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            AuctionMapper mapper = sqlSession.getMapper(AuctionMapper.class);

            int auctionId = RequestUtil.parseInt(request, "auctionId", 0);
            if(auctionId > 0) {
                mapper.deleteAuction(auctionId);
                sqlSession.commit();
            }
            // 删除成功后重定向回列表页，并保留当前页码
            response.sendRedirect(request.getContextPath() + "/do/pageList");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @RequestMapping(value = "/updateAuction")
    public void updateAuction(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            AuctionMapper mapper = sqlSession.getMapper(AuctionMapper.class);

            // 1. 获取表单数据
            Auction auction = new Auction();
            auction.setAuctionId(RequestUtil.parseInt(request, "auctionId", 0));
            auction.setAuctionName(request.getParameter("auctionName"));
            auction.setAuctionStartPrice(Double.parseDouble(request.getParameter("auctionStartPrice")));
            auction.setAuctionUpset(Double.parseDouble(request.getParameter("auctionUpset")));
            auction.setAuctionDesc(request.getParameter("auctionDesc"));

            // 2. 处理时间格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
            auction.setAuctionStartTime(sdf.parse(request.getParameter("auctionStartTime")));
            auction.setAuctionEndTime(sdf.parse(request.getParameter("auctionEndTime")));

            // 3. 处理文件上传
            Part filePart = request.getPart("auctionPicFile");
            if (filePart != null && filePart.getSize() > 0) {
                String fileName = filePart.getSubmittedFileName();
                String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
                String newFileName = UUID.randomUUID() + "." + fileExtension;

                String uploadPath = request.getServletContext().getRealPath("/uploads");
                Files.createDirectories(Paths.get(uploadPath));
                filePart.write(uploadPath + File.separator + newFileName);

                auction.setAuctionPic("uploads/" + newFileName);
                auction.setAuctionPicType(fileExtension); // 设置图片类型
            }

            // 4. 更新数据库
            mapper.updateAuction(auction);
            sqlSession.commit();

            // 5. 重定向回列表页
            response.sendRedirect(request.getContextPath() + "/do/pageList");

        } catch (Exception e) {
            e.printStackTrace();
            request.getRequestDispatcher("upAuction.jsp").forward(request, response);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @RequestMapping(value = "/selectById")
    public void selectById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        HttpSession session = request.getSession(false);
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            AuctionMapper mapper = sqlSession.getMapper(AuctionMapper.class);

            // 从请求参数获取 auctionId
            int auctionId = Integer.parseInt(request.getParameter("auctionId"));
            Auction auction = mapper.selectById(auctionId);

            // 将数据存入 request 作用域
            session.setAttribute("auction", auction);
            response.sendRedirect(request.getContextPath() + "/upAuction.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "查询失败");
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
}
